var defaultConfig = {
  maxWidth: 8000,
  maxHeight: 8000,
  backgroundStyle: '#CCC',
  textStyle: '#FFF',
  fontFamily: 'Impact',
  fontSizeParam: 5
};

/**
 * Generate image for placeholder use
 * url /genimg/400x300.png
 * url /genimg/400x300.jpg
 */
module.exports = {

  genImg: function (req, res, next) {

    config = defaultConfig;
    var regx = /^\/genImg\/(\d+)x(\d+)$/,
      match = req.url.match(regx),
      width,
      height,
      ext;
    if (!match) {
      return next();
    }

    width = parseInt(match[1], 10);
    height = parseInt(match[2], 10);

    if (width < 0 || width > config.maxWidth || height < 0 || height > config.maxHeight) {
      throw new Error('genimage: Size out of range');
      return;
    }

    var font_size = Math.round(Math.max(12, Math.min(Math.min(width, height) * 0.75, 0.75 * Math.max(width, height) / 12)))
    res.writeHead(200, {'Content-Type': 'image/svg+xml'});
    //res.end('<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none"><rect width="' + width + '" height="' + height + '" fill="#eee"/><text text-anchor="middle" x="' + width / 2 + '" y="' + height / 2 + '" style="fill:#aaa;font-weight:bold;font-size:' + font_size + 'px;font-family:Arial,Helvetica,sans-serif;dominant-baseline:central">' + width + 'x' + height + '</text></svg>');
    res.end('<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none"><rect width="' + width + '" height="' + height + '" fill="#eee"/><text text-anchor="middle" x="' + width / 2 + '" y="' + height / 2 + '" style="fill:#aaa;font-weight:bold;font-size:' + font_size + 'px;font-family:Arial,Helvetica,sans-serif;dominant-baseline:central">' + width + 'x' + height + '</text><head/></svg>')
  }
}
